/**
 * @Description:
 * @author 云离
 * @date: 2018/12/29
 */
import React, { Component } from 'react'
import {Form, Icon, Input, Button, Checkbox, Row, Col, Card} from 'antd'
import {withRouter} from 'react-router-dom'
import {FormattedMessage, injectIntl} from 'react-intl'
import defaultI18n from '../../../i18n/zh'
import {host} from '../../../config/config'
import md5 from 'md5-node'
import axios from '../../../apis/api'
import qs from 'qs'
import { connect } from 'react-redux'
import {actions} from '../../../reducers/system'

const mapStateToProps = (state, ownProps) => {
    return {
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        setUser: (user)=> dispatch(actions.setUser(user))
    }
}

class NormalLoginForm extends Component {

     state = {
         codeImg:  `${host}/captcha/captchaImage?type=math`,
         codeTime: '',
         loading: false,
         showCode: false,
         defaultHeight: 380,
         title: '管理台'
    }

    handleSubmit = (e) => {
        const that = this
        e.preventDefault();
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                const {userName, password, validateCode, phoneCode, rememberMe} = values
                const {showCode} = this.state
                this.setState({
                    loading: true
                })
                const body = {
                    username: userName,
                    password: md5(password),
                    validateCode: validateCode,
                    rememberMe: rememberMe,
                    phoneCode
                }
                try {
                    const needCodeResult = await axios.post('/needCode', qs.stringify({
                        username: userName
                    }))
                    if (needCodeResult.data !== 'noNeed') {
                        this.setState({
                            showCode: true
                        })
                        if (!showCode) {
                            this.setState({
                                loading: false
                            })
                            return
                        }
                    }
                    const result = await axios.post('/login', qs.stringify(body))
                    if (result.code === 0) {
                        // 登录成功
                        this.props.setUser(true)
                        setTimeout(() => {
                            that.props.history.replace('/main')
                        }, 300)
                    } else {
                        this.reflashCode()
                    }
                } catch (e) {
                    this.reflashCode()
                    this.setState({
                        loading: false
                    })
                }
            }
        });
    }
    componentDidMount () {
         axios.get('/title').then(data => {
             console.log(data)
             if (data.code === 0) {
                 this.setState({
                     title: data.data || '管理台'
                 })
             }
         })
    }

    reflashCode = () => {
         this.setState({
             codeTime: new Date().getTime()
         })
    }
    render() {
        const self = this
        const { getFieldDecorator } = this.props.form;
        const { codeImg, codeTime, loading, showCode, defaultHeight, title } = this.state
        const codeImgUrl = codeTime ? `${codeImg}&s=${codeTime}` : codeImg
        return (
            <Card title={title} className={'form'} style={{padding: 20, height: showCode? defaultHeight + 50: defaultHeight}}>
                <Form onSubmit={this.handleSubmit} className="login-form" autoComplete="off">
                    <Form.Item>
                        {getFieldDecorator('userName', {
                            rules: [{ required: true, message: self.props.intl.formatMessage({
                                    id: 'pleaseEnterUsername',
                                    defaultMessage: defaultI18n.pleaseEnterUsername
                                })}],
                        })(
                            <Input onClick={() => {
                                this.setState({
                                    showCode: false
                                })
                            }} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder={this.props.intl.formatMessage({
                                id: 'username',
                                defaultMessage: defaultI18n.username
                            })} autoComplete="off"/>
                        )}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('password', {
                            rules: [{ required: true, message: self.props.intl.formatMessage({
                                    id: 'pleaseEnterPassword',
                                    defaultMessage: defaultI18n.pleaseEnterPassword
                                })}],
                        })(
                            <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder={this.props.intl.formatMessage({
                                id: 'password',
                                defaultMessage: defaultI18n.password
                            })} autoComplete="off"/>
                        )}
                    </Form.Item>
                    {/*<Form.Item>*/}
                    {/*    {getFieldDecorator('validateCode', {*/}
                    {/*        rules: [{ required: true, message: '请输入验证码'}],*/}
                    {/*    })(*/}
                    {/*        <Row gutter={[16, 16]}>*/}
                    {/*            <Col span={12}><Input placeholder='验证码' autoComplete="off"/></Col>*/}
                    {/*            <Col span={12}><img  src={codeImgUrl} width={100} onClick={this.reflashCode}/></Col>*/}
                    {/*        </Row>*/}
                    {/*    )}*/}
                    {/*</Form.Item>*/}
                    {showCode? (
                        <Form.Item>
                            {getFieldDecorator('phoneCode', {
                                rules: [{ required: true, message: '请输入谷歌验证码'}],
                            })(
                                <Row gutter={[16, 16]}>
                                    <Col span={24}><Input placeholder='请输入谷歌验证码' autoComplete="off"/></Col>
                                </Row>
                            )}
                        </Form.Item>
                    ) : null}
                    <Form.Item>
                        {getFieldDecorator('rememberMe', {
                            valuePropName: 'checked',
                            initialValue: true,
                        })(<Checkbox>记住我</Checkbox>)}
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="login-form-button" style={{width: '100%'}} loading={loading}>
                            <FormattedMessage id="login" defaultMessage="登录" />
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        );
    }
}

export default withRouter(injectIntl(Form.create()(connect(mapStateToProps,mapDispatchToProps)(NormalLoginForm))))
